//
//  WLWebViewController.swift
//  swiftLiaoNing
//
//  Created by Visitor on 2017/5/23.
//  Copyright © 2017年 万利. All rights reserved.
//

import UIKit

class WLWebViewController: WLBaseViewController {
    var urlStr: String?
    var titleTextStr: String?
    var webView: UIWebView?
  
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        webView?.delegate = nil
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupWebViewStyle()
        setupUI()
    }
    
    private func setupWebViewStyle(){
        view.backgroundColor = RGB_S(c: 255)
        automaticallyAdjustsScrollViewInsets = false
        
        let titleBtn = UIButton.createButton(title: titleTextStr ?? "", titleColor: UIColor.white, font: 20, imageName: "navigation_back", backgroundImageName: "", target: self, action: #selector(titleBtnClick))
        titleBtn.frame = CGRect(x: 0, y: 10, width: 160, height: 35)
        titleBtn.imageEdgeInsets = UIEdgeInsetsMake(0, -15, 0, 0)
        navigationItem.leftBarButtonItem = UIBarButtonItem(customView: titleBtn)
    }
    
    ///swift3.0 新增 控制器返回 有 返回值
    func titleBtnClick() {
        webView?.delegate = nil
        stopWaitDialog()
        _ = navigationController?.popViewController(animated: true)
    }
    
    private func  setupUI(){
        let webView = UIWebView()
        webView.frame = CGRect(x: 0, y: 0, width: M_S.width, height: M_S.height - 64)
        webView.backgroundColor = RGB_S(c: 255)
        webView.delegate = self
        webView.sizeToFit()
        view.addSubview(webView)
        self.webView = webView
        
        if urlStr?.characters.count == 0 {
            showTextDialog(text: "无效链接")
            return
        }
     
        startWaitDialog()
        let urls = URL(string: urlStr!)
        let request = URLRequest(url: urls!)
        webView.loadRequest(request)
    }
}

extension WLWebViewController: UIWebViewDelegate {
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        stopWaitDialog()
    }
    
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        return true
    }
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        DLog(log: error)
        stopWaitDialog()
    }
    
    
}
